﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DeliveryService
{
    public class BLStudents
    {

        public bool IsStudentsExists(string name, string studentNo)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                if (string.IsNullOrEmpty(name))
                    throw new ArgumentNullException("student name is null.");
                return db.Students.Any(s => s.name.Trim() == name.Trim() && s.studentNumber == studentNo);
            }
        }

        public bool IsRealStudents(string studentName, string studentNo)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                if (string.IsNullOrEmpty(studentName))
                    throw new ArgumentNullException("student name can not be null.");
                if (string.IsNullOrEmpty(studentNo))
                    throw new ArgumentNullException("student number can not be null.");
                //if (!IsStudentsExists(studentName,studentNo))
                //    throw new ArgumentNullException("can not find this student : " + studentName);
                return db.Real_Students.Any(s => s.Student_Name.Trim() == studentName.Trim() && s.Students_Number == studentNo);
            }
        }

        public bool IsPhoneExisits(string phone)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                return db.Students.Any(x => x.phoneNumber == phone);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="studentsNo"></param>
        /// <param name="phone"></param>
        /// <param name="SchoolId"></param>
        /// <param name="password"></param>
        /// <returns>
        /// -1:未知错误
        /// 0:注册成功
        /// 1:此学生已存在于学生表中，不可重复注册
        /// 2:学号和姓名不匹配
        /// 3:数据库中不存在此学生的真实信息
        /// 4:此学生信息已被注册过，不能再注册
        /// 5:手机号已被注册
        /// </returns>
        public int Register(string name, string studentsNo, string phone, int SchoolId, string password)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                try
                {
                    if (IsStudentsExists(name, studentsNo))
                        return 1;
                    //throw new ArgumentException(name + " is already exists.");
                    var real = db.Real_Students.SingleOrDefault(st => st.Students_Number == studentsNo);
                    if (real == null)
                        return 3;
                    if (real.Student_Name.Trim() != name.Trim())
                        return 2;
                    if (real.IsReister == 1)
                        return 4;
                    if (IsPhoneExisits(phone))
                        return 5;

                    Real_Student rs = new Real_Student();
                    Student s = new Student();
                    s.name = name;
                    s.studentNumber = studentsNo;
                    s.phoneNumber = phone;
                    s.School = db.Schools.SingleOrDefault(h => h.school_Id == SchoolId);
                    s.password = password;
                    db.Students.InsertOnSubmit(s);
                    real.IsReister = 1;
                    db.SubmitChanges();
                    return 0;
                }
                catch (Exception)
                {
                    return -1;
                    // throw;
                }
            }

        }

        /// <summary>
        /// 不需要学号的注册
        /// </summary>
        /// <param name="name">学生名</param>
        /// <param name="phone">电话号码</param>
        /// <param name="SchoolId">学校ID</param>
        /// <param name="password">密码</param>
        /// <returns>
        /// return 1: 电话号码已注册
        /// return 0：注册成功
        /// return -1： 未知错误
        /// </returns>
        public int RegisterWithoutStudentNo(string name, string phone, int SchoolId, string password)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                try
                {
                    if (IsPhoneExisits(phone))
                        return 1;
                    Real_Student rs = new Real_Student();
                    Student s = new Student();
                    s.name = name;
                    s.phoneNumber = phone;
                    s.School = db.Schools.SingleOrDefault(h => h.school_Id == SchoolId);
                    s.password = password;
                    db.Students.InsertOnSubmit(s);
                    db.SubmitChanges();
                    return 0;
                }
                catch (Exception)
                {
                    return -1;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="password"></param>
        /// <returns>
        /// -1:不存在此手机号的注册信息
        /// -2:密码错误
        /// >0: 登陆成功，返回学生ID
        /// </returns>
        public int StudentsLoginByPhone(string phone, string password)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                if (string.IsNullOrEmpty(phone))
                    throw new ArgumentException("phone number is null.");

                if (string.IsNullOrEmpty(password))
                    throw new ArgumentException("password is null.");

                var user = db.Students.SingleOrDefault(s => s.phoneNumber == phone);

                if (user == null)
                    return -1;
                //throw new ArgumentException("phone number " + phone + " can not found");
                if (user.password == password)
                    return user.Students_Id;
                else return -2;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="studentNo"></param>
        /// <param name="password"></param>
        /// <returns>
        /// -1:用户名错误：不存在此学号的注册信息
        /// -2:密码错误
        /// >0: 登陆成功，返回学生ID
        /// </returns>
        public int StudentsLogin(string studentNo, string password)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                if (string.IsNullOrEmpty(studentNo))
                    throw new ArgumentException("student number is null.");

                if (string.IsNullOrEmpty(password))
                    throw new ArgumentException("password is null.");

                var user = db.Students.SingleOrDefault(s => s.studentNumber == studentNo);

                if (user == null)
                    return -1;

                if (user.password == password)
                    return user.Students_Id;
                else return -2;
            }

        }

        public string GetBackPassword(string studentNo, string phone)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                if (string.IsNullOrEmpty(studentNo))
                    throw new ArgumentException("student number is null.");

                if (string.IsNullOrEmpty(phone))
                    throw new ArgumentException("phone number is null.");

                var student = db.Students.SingleOrDefault(s => s.studentNumber == studentNo && s.phoneNumber == phone);
                if (student == null)
                    throw new ArgumentException("can not found this user.");
                return student.password;
            }
        }

        public MStudent GetStudentByStuNo(string stuNo)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                var stu = db.Students.Where(S => S.studentNumber == stuNo)
                            .Select(s => new MStudent
                            {
                                StudentID = s.Students_Id,
                                Name = s.name,
                                Password = s.password,
                                Address = s.defaultAddress,
                                Phone = s.phoneNumber,
                                PhotoUrl = s.icon,
                                SchoolName = s.School.school_name,
                                Sex = s.sex.HasValue ? s.sex.Value : -1,
                                StudentNumber = s.studentNumber,
                                Xingyu = s.Xingyu.HasValue ? s.Xingyu.Value.ToString() : "0"
                            }).SingleOrDefault();
                if (stu == null)
                    throw new ArgumentException("can not found this student information");
                return stu;
            }
        }

        public MStudent GetStudentByPhone(string phone)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                var stu = db.Students.Where(S => S.phoneNumber == phone)
                            .Select(s => new MStudent
                            {
                                StudentID = s.Students_Id,
                                Name = s.name,
                                Password = s.password,
                                Address = s.defaultAddress ?? "",
                                Phone = s.phoneNumber ?? "",
                                PhotoUrl = s.icon ?? "",
                                SchoolName = s.School.school_name,
                                Sex = s.sex.HasValue ? s.sex.Value : -1,
                                StudentNumber = s.studentNumber,
                                Xingyu = s.Xingyu.HasValue ? s.Xingyu.Value.ToString() : "0"
                            }).SingleOrDefault();
                if (stu == null)
                    throw new ArgumentException("can not found this student information");
                return stu;
            }
        }

        /// <summary>
        /// 修改学生密码
        /// </summary>
        /// <param name="studentId">学生ID</param>
        /// <param name="oldPassword">原密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>
        /// 1:修改成功
        /// 2:原密码错误
        /// 3:新密码为空
        /// </returns>
        public int ChangeStudentPassword(int studentId, string oldPassword, string newPassword)
        {
            if (string.IsNullOrEmpty(newPassword))
                return 3;
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                var stu = db.Students.SingleOrDefault(s => s.Students_Id == studentId);
                if (stu.password != oldPassword)
                    return 2;
                stu.password = newPassword;
                db.SubmitChanges();
                return 1;
            }
        }

        // 获取所有学生的列表，需要特定的用户名和密码验证
        public string GetAllStudents(string phone, string password)
       // public string GetAllStudents()
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                # region 验证是否有权限

                if (string.IsNullOrEmpty(phone))
                {
                    throw new ArgumentException("phone number is null.");
                }

                if (string.IsNullOrEmpty(password))
                {
                    throw new ArgumentException("password is null.");
                }

                var user = db.Students.SingleOrDefault(s => s.phoneNumber == phone);

                if (user == null)
                    throw new ArgumentException("手机号不存在.");
                //throw new ArgumentException("phone number " + phone + " can not found");
                if (user.password != password)
                {
                    throw new ArgumentException("密码错误");
                }
                else if (phone != "18626373423")
                {
                    throw new Exception("改账号没有获取全部账号的权限");
                }

                #endregion

                // 如果前面验证通过，则返回所有注册用户
                var stus = db.Students
                            .Select(s => new
                            {
                                StudentID = s.Students_Id,
                                Name = s.name,
                                Phone = s.phoneNumber ?? "",
                            }).OrderByDescending(s => s.StudentID);

                return JsonConvert.SerializeObject(stus);
            }
        }

    }
}